package com.appkudos;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;


import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class MyApps extends Activity implements ViewBinder{
    // list view for displaying the installed apps
	private ListView lv;
	private ArrayList list;
	private PackageManager pm;
	private Activity PARENTACTIVITY;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PARENTACTIVITY = this;
        // set content view to apps_view xml
        setContentView(R.layout.apps_view);       
        
        // get list view from layout
        lv=(ListView)findViewById(R.id.list);
        
        // get installed apps from the device
        pm = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List apps = pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);  
        Iterator i = apps.iterator();
		
	    // initialize the list
		initList(pm, i);
		
		// when item is clicked go to app page
	    lv.setOnItemClickListener(new OnItemClickListener() {
	           public void onItemClick(AdapterView<?> parent, View view,
	               int position, long id) {
	             // When clicked, show a toast with the TextView text
	        	 ListItem item = (ListItem) list.get(position);
//	             Toast.makeText(getApplicationContext(), "position is "+position+" name is "+ item.text,
//	             Toast.LENGTH_SHORT).show();
	                Intent intent = new Intent(PARENTACTIVITY, App.class);
	                intent.putExtra("app_name", item.text);
	        		startActivity(intent);
	             
	           }
	    });
	       
		// set filter on listview
		lv.setTextFilterEnabled(true);
   }
    
    /**
     * populate the list with installed apps
     * @param pm - package manager
     * @param i - iterator
     */
    private void initList(PackageManager pm, Iterator i) {
    	// initialize variable for manipuation
    	ResolveInfo rInfo; 
    	Map<String, ListItem> itemData;
    	List<Map<String, ListItem>> listData = new ArrayList<Map<String, ListItem>>();
    	list = new ArrayList<ListItem>();
    	ListItem listItem1;
    	
    	// extract app data and put it into a list 
    	while (i.hasNext()) {
    		rInfo = (ResolveInfo) i.next(); 
    	
    		listItem1 = new ListItem();
    	    listItem1.text = rInfo.activityInfo.applicationInfo.loadLabel(pm).toString();
    	    listItem1.icon = rInfo.activityInfo.applicationInfo.loadIcon(pm);
    	    listItem1.rInfo = rInfo;
    	    //TODO - get checkbox value from database
    	    listItem1.check = false;
    	    list.add(listItem1);
        }    
    	
    	// sort the list of apps by title
    	Collections.sort(list);
    	
    	// put the apps into a hashmap (used for input by simple adapter)
    	for(int j=0; j<list.size();j++){
    		itemData = new HashMap<String, ListItem>(1);
    		listItem1 = (ListItem) list.get(j);
    		//itemData.put("app_text", listItem1);
    		itemData.put("app_list_linearLayout1", listItem1);
    		listData.add(itemData);
    	}    

    	// bind simple adapter to the list view
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.app_list,
                new String[] {
                    "app_list_linearLayout1"
                }, new int[] {
                    R.id.app_list_linearLayout1
                });
        
        // bind viewBinder to adapter and set adapter to listview
        simpleAdapter.setViewBinder(this);
        lv.setAdapter(simpleAdapter);
    }
    
    @Override
    public boolean setViewValue(View view, Object data, String stringRepresetation) {  	
    	// get data for the row
    	ListItem listItem = (ListItem) data;
        LinearLayout layout = (LinearLayout) view;
        
        // bind information to the textbox and icon
        TextView tv1 = (TextView) layout.findViewById(R.id.app_text);
        tv1.setText(listItem.text);
        tv1.setCompoundDrawablesWithIntrinsicBounds(listItem.icon, null, null, null);
        
        // set the checkbox (checked if flagged as fav)
        CheckBox box = (CheckBox) layout.findViewById(R.id.fav_check);
        box.setChecked(listItem.check);
        box.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v)
            {
                //TODO - save app as favourite
          	  
          	  //((CheckBox) v).toggle();  
            }
        });

        return true;
    }

    // private container class for keeping the app data
    private class ListItem implements Comparable<ListItem>{
        public String text;
        public Drawable icon;
        public Boolean check;
        public ResolveInfo rInfo;
        
		@Override
		public int compareTo(ListItem item) {
	        return text.compareTo(item.text);
	    }
    }
}
